import * as types from '../mutation-types'
import DEVICE_TYPES from 'config/device-types'
import _ from 'lodash'
import ELEDATA from 'static/data/devices/electric.json'
import filters from 'filters'
import PRODUCTIDS from 'config/product-ids'
import api from 'api'
import ELEALERTDATA from 'static/data/devices/electricAlert.json'
import store from 'src/store' // vuex store instance

// 定义变量,等所有请求都返回之后再丢到getters中
let eleNumber = 0
let eleArr = []
// 定义一些方法
const eleMethods = {
// 判断后台返回的数据是否超出最大和最小值,超出后渲染一个默认值
  stateCommit (num) {
    if (num > 10000 || num < -10000) {
      return num > 10000 ? 10000 : -10000
    }
    return num
  },
  // 检查三相设备是否异常
  isPhaseAlert (phase) {
    let res = false
    for (let attr in ELEALERTDATA) {
      if (eleMethods.attrIsAlert(attr, phase)) {
        res = true
        break
      }
    }
    return res
  },
  // 检查某个属性是否异常
  attrIsAlert (attr, phase) {
    if (phase) {
      if (!phase[attr]) {
        return false
      }
      if (phase[attr] - 0 > ELEALERTDATA[attr].max || phase[attr] - 0 < ELEALERTDATA[attr].min) {
        return true
      }
      return false
    }
  },
  getDeviceMsgs (type) {
    let productId = PRODUCTIDS[type]
    let deviceIds = []
    ELEDATA.devices.forEach((device) => {
      if (device.type === type) {
        deviceIds.push(device.id)
      }
    })
    return {productId, deviceIds}
  },

  getDeviceMsg (type) {
    let productId = PRODUCTIDS[type]
    let deviceId
    ELEDATA.devices.forEach((device) => {
      if (device.type === type) {
        deviceId = device.id
      }
    })
    return {productId, deviceId}
  }
}

// initial state
const state = {
  devices: []
}

// actions
const actions = {
  updateElectricalDeviceStatusData ({ commit }, _self) {
    let switchId = []
    let tempId = []
    ELEDATA.forEach(element => {
      let swi = _.filter(element.devices, (item) => {
        return item.type === DEVICE_TYPES.SWITCH
      })
      swi['title'] = element.title
      swi['area'] = element.area
      switchId.push(swi)
      let tem = _.filter(element.devices, (item) => {
        return item.type === DEVICE_TYPES.TEMP_HUMIDITY
      })
      tem['title'] = element.title
      tem['area'] = element.area
      tempId.push(tem)
    })
    switchId.forEach(element => {
      element.forEach(item => {
        // I/O开关量检测
        api.device.getVDevice(PRODUCTIDS[DEVICE_TYPES.SWITCH], item.id).then((res) => {
          let datapoints = res.data
          let {
            'online': deviceOnLine,
            '4': deviceStatus
          } = datapoints

          // 将数据添加如vuex
          let obj = {
            id: item.id,
            type: DEVICE_TYPES.SWITCH,
            online: deviceOnLine,
            data: {
              '4': deviceStatus
            },
            room: element.title, // 所属位置
            area: element.area, // 所属项目
            serialNumber: item.serialNumber // 序号
          }
          commit(types.UPDATE_ELECTRICAL_DEVICE_STATUS, obj)
        }).catch((res) => {
          _self.handleError(res)
          console.log(res)
        })
      })
    })

    tempId.forEach(element => {
      element.forEach(item => {
        // 智能温湿度变送器
        api.device.getVDevice(PRODUCTIDS[DEVICE_TYPES.TEMP_HUMIDITY], item.id).then((res) => {
          let datapoints = res.data
          let {
            '13': temperature,
            '14': humidity
          } = datapoints

          // this.deviceDatas.temperature = filters.toFixed(this.stateCommit(temperature)) || '-'
          // this.deviceDatas.humidity = filters.toFixed(this.stateCommit(humidity)) || '-'

          // 将数据添加如vuex
          let obj = {
            id: item.id,
            type: DEVICE_TYPES.TEMP_HUMIDITY,
            isWarnning: false, // 是否告警
            data: {
              '13': temperature,
              '14': humidity
            },
            room: element.title, // 所属位置
            area: element.area, // 所属项目
            serialNumber: item.serialNumber // 序号
          }
          commit(types.UPDATE_ELECTRICAL_DEVICE_STATUS, obj)
        }).catch((res) => {
          _self.handleError(res)
          console.log(res)
        })
      })
    })
  },
  // 三相电（数据与是否告警是否在线等状态）
  updateElectricalStatistics ({ commit }, _self) {
    let phaseId = []
    ELEDATA.forEach(element => {
      let res = []
      res = _.filter(element.devices, (item) => {
        return item.type === DEVICE_TYPES.PHASE
      })
      res['title'] = element.title
      res['area'] = element.area
      phaseId.push(res)
    })
    phaseId.forEach(element => {
      element.forEach(item => {
        let productId = PRODUCTIDS[DEVICE_TYPES.PHASE]
        // 智能三相电力监控仪
        api.device.getVDevice(productId, item.id).then((res) => {
          eleNumber++
          let datapoints = res.data
          let {
            '101': aVoltage,
            '102': aElectric,
            '103': bVoltage,
            '104': bElectric,
            '105': cVoltage,
            '106': cElectric,
            '107': power,
            '108': psum
          } = datapoints

          let obj = {}
          obj.id = item.id
          obj.aVoltage = filters.toFixed(eleMethods.stateCommit(aVoltage), 2) || '-'
          obj.bVoltage = filters.toFixed(eleMethods.stateCommit(bVoltage), 2) || '-'
          obj.cVoltage = filters.toFixed(eleMethods.stateCommit(cVoltage), 2) || '-'
          obj.bElectric = filters.toFixed(eleMethods.stateCommit(bElectric), 2) || '-'
          obj.aElectric = filters.toFixed(eleMethods.stateCommit(aElectric), 2) || '-'
          obj.cElectric = filters.toFixed(eleMethods.stateCommit(cElectric), 2) || '-'
          obj.power = filters.toFixed(eleMethods.stateCommit(power), 2) || '-'
          obj.psum = filters.toFixed(eleMethods.stateCommit(psum), 2) || '-'
          let oj = {
            id: item.id,
            type: DEVICE_TYPES.PHASE,
            online: res.data.online,
            isWarnning: false,
            data: {
              'aVoltage': aVoltage,
              'aElectric': aElectric,
              'bVoltage': bVoltage,
              'bElectric': bElectric,
              'cVoltage': cVoltage,
              'cElectric': cElectric,
              'power': power,
              'psum': psum
            },
            room: element.title, // 所属位置
            area: element.area, // 所属项目
            serialNumber: item.serialNumber // 序号
          }
          commit(types.UPDATE_ELECTRICAL_STATISTICS, oj)
        }).catch((err) => {
          eleNumber++
          _self.handleError(err)
          console.log(err)
        })
      })
    })
  }
}

// getters
const getters = {
  eleTempHumidity (state) {
    // return _.filter(state.devices, (item) => {
    //   return item.type === DEVICE_TYPES.TEMP_HUMIDITY
    // })
    switch (store.state.route.path.split('/')[1]) {
      case ':0':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.TEMP_HUMIDITY && item.area === '天悦'
        })
      case ':1':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.TEMP_HUMIDITY && item.area === '香槟'
        })
      case ':2':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.TEMP_HUMIDITY && item.area === '香槟'
        })
      case ':3':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.TEMP_HUMIDITY && item.area === '香槟'
        })
    }
  },
  phase (state) {
    switch (store.state.route.path.split('/')[1]) {
      case ':0':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.PHASE && item.area === '天悦'
        })
      case ':1':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.PHASE && item.area === '香槟'
        })
      case ':2':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.PHASE && item.area === '香槟'
        })
      case ':3':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.PHASE && item.area === '香槟'
        })
    }
  },
  // 用于首页做统计
  phaseHome (state) {
    return _.filter(state.devices, (item) => {
      return item.type === DEVICE_TYPES.PHASE
    })
  },
  switch (state) {
    switch (store.state.route.path.split('/')[1]) {
      case ':0':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.SWITCH && item.area === '天悦'
        })
      case ':1':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.SWITCH && item.area === '香槟'
        })
      case ':2':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.SWITCH && item.area === '香槟'
        })
      case ':3':
        return _.filter(state.devices, (item) => {
          return item.type === DEVICE_TYPES.SWITCH && item.area === '香槟'
        })
    }
  }
}

// mutations
const mutations = {
  [types.UPDATE_ELECTRICAL_DEVICE_STATUS] (state, deviceStatus) {
    if (!deviceStatus.id) {
      return
    }

    let finded = _.find(state.devices, (item) => {
      return item.id === deviceStatus.id
    })
    if (finded) {
      state.devices = _.filter(state.devices, (item) => {
        return item.id !== deviceStatus.id
      })
    }
    state.devices.push(deviceStatus)
  },
  [types.UPDATE_ELECTRICAL_STATISTICS] (state, obj) {
    if (!obj.id) {
      return
    }
    let finded = _.find(state.devices, (item) => {
      return item.id === obj.id
    })
    if (finded) {
      state.devices = _.filter(state.devices, (item) => {
        return item.id !== obj.id
      })
    }
    // 将返回的数据先存起来，等到所有都接收完成再丢进去getters中
    if (eleNumber >= 30) {
      state.devices = _.concat(state.devices, eleArr)
      eleNumber = 0
      eleArr = []
    } else {
      eleArr.push(obj)
    }
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
